<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/15
 * 描述:
 */
declare(strict_types=1);

namespace app\api\controller;

use app\BaseController;
use app\result\UserResult;
use app\service\ChatWorkerService;
use think\App;
use think\facade\Route;

class BaseIndex extends BaseController
{
    protected $objResult;
    protected $user_id;
    protected $user_code;
    protected $token;
    protected $unauthorized = [];//不需要token验证的接口

    protected $param = [];


    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->param = request()->filter('trim,htmlspecialchars')->param();
        $this->check_token();
        ChatWorkerService::init_gateway();
    }

    public function check_token()
    {
        $this->token = request()->header('authorization');
        $action = request()->action();
        $controller = strtolower(request()->controller());
        $authStr = strtolower($controller . '@' . $action);

        $isUnauthorized = false;
        if (is_array($this->unauthorized)) {
            $isUnauthorized = in_array($authStr, $this->unauthorized);
        } else if (is_string($this->unauthorized)) {
            if ($this->unauthorized === '*') {
                $isUnauthorized = true;
            } else {
                // 处理逗号分隔的字符串
                $unauthorizedList = explode(',', $this->unauthorized);//可以是“login@reg,login@login"
                $isUnauthorized = in_array($authStr, $unauthorizedList);
            }
        }

        // 如果需要验证权限
        if (!$isUnauthorized) {
            // 如果提供了token，则验证格式
            if ($this->token) {
                if (stripos($this->token, 'Bearer') !== 0) {
                    data_return('token格式错误', 401);
                }
                $this->token = trim(str_replace('Bearer', '', $this->token));
            } else {
                // 没有提供token且需要验证权限
                data_return('请先登录', 401);
            }

            // 解析token获取用户信息
            if (!empty($this->token)) {
                $userDecode = (new UserResult())->get_token_user($this->token, 'user_id,user_code');
                $user = $userDecode['code'] === 0 ? $userDecode['data'] : [];
                if ($user) {
                    $this->user_code = $user['user_code'];
                    $this->user_id = $user['user_id'];
                } else {
                    data_return('登录过期，请重新登录', 401, $this->token);
                }
            } else {
                data_return('认证信息不能为空', 401);
            }
            if (!$this->user_id) {
                data_return('登录过期，请重新登录', 401, $this->token);
            }
        } else if ($this->token) {
            if (stripos($this->token, 'Bearer') !== 0) {
                $this->token = null; // 格式错误则忽略token
                return;
            }
            $this->token = trim(str_replace('Bearer', '', $this->token));

            // 尝试解析token但不强制要求成功
            if (!empty($this->token)) {
                $userDecode = (new UserResult())->get_token_user($this->token, 'user_id,user_code');
                $user = $userDecode['code'] === 0 ? $userDecode['data'] : [];
                if ($user) {
                    $this->user_code = $user['user_code'];
                    $this->user_id = $user['user_id'];
                }
            }
        }
    }
}
